package xnj.lazydog.btcontroller;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileUtils;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import xnj.lazydog.btcontroller.ControlViews.ItemProject;
import xnj.lazydog.btcontroller.ControlViews.Project;
import xnj.lazydog.btcontroller.ControlViews.ProjectList;
import xnj.lazydog.btcontroller.ObjectFile.ObjectFile;

public class FileHandlerActivity extends Activity {

    private static final String TAG = "FileHandlerActivity";

    class UriFile {
        String fullPath = null;
        String name = null;
        Uri uri = null;
        File file;
        UriFile(Uri uri)
        {
            this.uri = uri;

            if(uri==null)
                return;
            Log.w(TAG, "UriFile: " +uri.getPath()+" "+uri.getScheme());
            if("content".equals(uri.getScheme()))
            {
                String [] filePathCol = {MediaStore.MediaColumns.DISPLAY_NAME,MediaStore.MediaColumns.DATA};
                ContentResolver resolver = getContentResolver();
                Cursor cursor = resolver.query(uri,filePathCol,null,null,null);

                if(cursor!=null)
                {
                    Log.w(TAG, "UriFile: cursor not null" );
                    cursor.moveToFirst();

                    if(cursor.getColumnCount()>1)
                        fullPath = cursor.getString(1);

                    name = cursor.getString(0);

                    cursor.close();
                }else
                {
                    Log.w(TAG, "UriFile: cursor  null" );
                }
            }
            if("file".equals(uri.getScheme())||fullPath==null)
            {
                Log.w(TAG, "UriFile: full path null" );
                fullPath = uri.getPath();
            }


            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                file = new File(fullPath);

                if (!file.exists()) {
                    fullPath = fullPath.replace("/root", "");
                    file = new File(fullPath);
                }
            }else
            {
                Log.w(TAG, "UriFile: API Q");
                file = uriToFileApiQ(uri);
                fullPath = file.getAbsolutePath();
            }

            Log.w(TAG, "UriFile: "+file.length()+"  "+fullPath +"  "+file.exists());



        }
    }

    Button cancelButton,importButton;
    UriFile uriFile;

    ProjectList projectList;

    void loadProjectListOptions()
    {

        projectList =(ProjectList) ObjectFile.loadObject(this,"project_list");
        if(projectList==null)
            projectList = new ProjectList();
        ItemProject tip1,tip2;
        for(int i=1;i<projectList.itemProjects.size();i++)
        {
            for(int j=0;j<i;j++) {
                if(projectList.itemProjects.get(j).time<projectList.itemProjects.get(j+1).time)
                {
                    tip2 = projectList.itemProjects.get(j+1);
                    projectList.itemProjects.remove(j+1);
                    projectList.itemProjects.add(j,tip2);
                }
            }
        }

    }

    String projectName;


    @RequiresApi(api = Build.VERSION_CODES.Q)
    public File uriToFileApiQ(Uri uri) {
        File file =null;
        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
            file =new File(uri.getPath());

        }else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            ContentResolver contentResolver =this.getContentResolver();
            Cursor cursor =contentResolver.query(uri,null,null,null,null);
            if (cursor.moveToFirst()) {
                String displayName =cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                try {
                    InputStream is =contentResolver.openInputStream(uri);
                    File cache =new File(this.getExternalCacheDir().getAbsolutePath(),displayName);
                    FileOutputStream fos =new FileOutputStream(cache);
                    FileUtils.copy(is,fos);
                    file =cache;
                    fos.close();
                    is.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loadProjectListOptions();

        setContentView(R.layout.import_layout);

        boolean fileOK = false;

        if(Intent.ACTION_VIEW.equals(getIntent().getAction())) {
            //Log.w(TAG, "onCreate: uri file"+getPathFromUri(this,getIntent().getData()));
            Uri u = getIntent().getData();

            uriFile = new UriFile(getIntent().getData());


            String name = uriFile.name;
            String ss[] = name.split("_");
            if(ss.length>=3&&uriFile.name.endsWith(".pro"))
            {
                fileOK = true;
                projectName = ss[0];
            }
        }

        TextView textView = findViewById(R.id.import_ask);

        String askStr = "是否导入调试工程 "+projectName+" ?";
        textView.setText(askStr);

        if(!fileOK) {
            Toast.makeText(FileHandlerActivity.this, "文件异常", Toast.LENGTH_SHORT).show();
            finishAfterTransition();
        }

        cancelButton = findViewById(R.id.cancel_button);
        importButton = findViewById(R.id.import_button);

        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(FileHandlerActivity.this ,"放弃导入工程",Toast.LENGTH_SHORT).show();
                finishAfterTransition();
            }
        });

        importButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //ButtonOptionsUtil.loadOptionsFromFile(FileHandlerActivity.this, uriFile.file);
                //Project project = (Project) ObjectFile.loadObject(FileHandlerActivity.this,uriFile.fullPath);
                boolean ok = false;
                if(uriFile.file!=null&&uriFile.file.exists()) {
                    ok = projectList.addProject(FileHandlerActivity.this, uriFile.file);
                    Log.w(TAG, "onClick: AddProject"+projectList.itemProjects.size() );
                }


                if(ok) {
                    sendBroadcast(new Intent("FILE_UPDATE_BUTTON"));
                    ObjectFile.saveObject(FileHandlerActivity.this,"project_list",projectList);
                    Toast.makeText(FileHandlerActivity.this, "成功导入工程", Toast.LENGTH_SHORT).show();
                }else
                    Toast.makeText(FileHandlerActivity.this ,"导入失败",Toast.LENGTH_SHORT).show();

                new Thread(){
                    @Override
                    public void run() {
                        try {
                            sleep(1200);
                        }catch (InterruptedException e)
                        {
                            e.printStackTrace();
                        }
                        finishAfterTransition();
                    }
                }.start();
                //finishAfterTransition();
            }
        });


    }
}
